package com.yellow.cloud.gateway.service;

import com.alibaba.fastjson.JSON;
import com.yellowframework.cloud.common.constant.Constants;
import com.yellowframework.cloud.domain.security.AuthToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @version 1.0
 **/
@Service
public class AuthService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 从头取出jwt令牌
     * @author Hao.
     * @date 2020/10/27 18:25
     * @param request
     * @return java.lang.String
     */
    public String getJwtFromHeader(ServerHttpRequest request){
        //取出头信息
        String authorization = request.getHeaders().getFirst("Authorization");
        if(StringUtils.isEmpty(authorization)){
            return null;
        }
        if(!authorization.startsWith(Constants.TOKEN_PREFIX)){
            return null;
        }
        //取到jwt令牌
        String jwt = authorization.substring(7);
        return jwt;
    }
    /**
     * 从cookie取出身份令牌
     * @author Hao.
     * @date 2020/10/27 18:26
     * @param request
     * @return java.lang.String
     */
    public String getTokenFromCookie(ServerHttpRequest request){
        final HttpCookie uid = request.getCookies().getFirst("uid");
        if(Objects.isNull(uid)){
            return null;
        }
        String access_token = uid.getValue();
        if(StringUtils.isEmpty(access_token)){
            return null;
        }
        return access_token;
    }

    /**
     * 查询令牌的有效期
     * @author Hao.
     * @date 2020/10/27 18:26
     * @param access_token 身份令牌
     * @return long
     */
     public long getExpire(String access_token){
        //key
         String key = "user_token:"+access_token;
         Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
         return expire;
     }

    /**
     * 校验令牌
     * @author Hao.
     * @date 2020/10/27 18:26
     * @param access_token 身份令牌
     * @param jwt 身份信息
     * @return long
     */
     public boolean invalid(String access_token, String jwt){
        //key
         String key = "user_token:"+access_token;
         final AuthToken token = JSON.parseObject(stringRedisTemplate.opsForValue().get(key), AuthToken.class);
         return !jwt.equals(token.getJwt_token());
     }
}
